clear;
exec('circshift.sci');
stacksize('max');

N = 512;

//%%%%%%%%%%%%%%%%% формирование сигналов %%%%%%%%%%%%%%%%%

 Xadc = csvRead('D:\Program Files\ADC_data\nois1_50dBm_GN22.csv');
//[x1, x2, x3, x4] = read_hex_data('D:\Program Files\ADC_data\nois3_60dBm_GN22\',1);
//Xadc = [x1; x2; x3; x4];

x = Xadc(:,1:$);//данные по строкам I-Q I-Q и т.д.
[num, len] = size(x);

num = 10;

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

//%%%%%%%%%%%%%%%%%%%% MATRIX %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

main = [1 2];
//E = x(main,:);
E = [sum(x(1:2:$,:), 'r');sum(x(2:2:$,:), 'r')];
E_ = E(:,1:N);
//%  ???? ????????
//% Z = [x ; circshift(x',1)'; circshift(x',2)'; circshift(x',3)'; circshift(x',4)'; circshift(x',5)'];
//% Z(main,:) = [];
Z_data = x;
//Z_data(main,:) = [];
Z_data = Z_data(1:(num-2),:);
n_delay = 0;
step_delay = 1;
Z = Z_data;

for i = 1:n_delay
    Z = [Z; circshift(Z_data',-i)'];
end

Z_ = zeros((num-2)*(n_delay+1),N);
Z_(1:(num-2),:) = Z(1:(num-2),1:N);
for i = 1:step_delay:n_delay
    Z_(i*(num-2)+1:(i+1)*(num-2), :) = Z(i*(num-2)+1:(i+1)*(num-2), 1:N);
    
    for j=2:step_delay
        if i+j-1 > n_delay then
            continue;
        end
        Z_((i+j-1)*(num-2)+1:(i+j)*(num-2), :) = circshift( Z(i*(num-2)+1:(i+1)*(num-2), 1:N)', -(j-1))';
    end
end

Rxx = Z_*Z_';
Rxd = E_*Z_';
//pause
invRxx = inv(Rxx);
wm = Rxd*invRxx;
out = E - wm*Z;
db = 20*log10(stdev(E(1,:))/stdev(out(1,:)));
disp(db);
db = 20*log10(stdev(E(2,:))/stdev(out(2,:)));
disp(db);
disp(stdev(out(1,:)));
disp(stdev(out(2,:)));

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
S = invRxx;
US = triu(S);
[row col] = size(S);
idx = zeros(row,col);
for row = 1:size(S,'r')
    for col = row:size(S,'c')
        c = size(find(US == S(row,col)),'c');
        if c > 1 then
            idx(row,col) = c;
        end
    end
end
